<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>7.12. MVC Exceptions</title>
<link rel="stylesheet" href="dbstyle.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.72.0">
<link rel="start" href="index.html" title="Programmer's Reference Guide">
<link rel="up" href="zend.controller.html" title="Chapter 7. Zend_Controller">
<link rel="prev" href="zend.controller.modular.html" title="7.11. Using a Conventional Modular Directory Structure">
<link rel="next" href="zend.controller.migration.html" title="7.13. Migrating from Previous Versions">
<link rel="chapter" href="introduction.html" title="Chapter 1. Introduction to Zend Framework">
<link rel="chapter" href="zend.acl.html" title="Chapter 2. Zend_Acl">
<link rel="chapter" href="zend.auth.html" title="Chapter 3. Zend_Auth">
<link rel="chapter" href="zend.cache.html" title="Chapter 4. Zend_Cache">
<link rel="chapter" href="zend.config.html" title="Chapter 5. Zend_Config">
<link rel="chapter" href="zend.console.getopt.html" title="Chapter 6. Zend_Console_Getopt">
<link rel="chapter" href="zend.controller.html" title="Chapter 7. Zend_Controller">
<link rel="chapter" href="zend.currency.html" title="Chapter 8. Zend_Currency">
<link rel="chapter" href="zend.date.html" title="Chapter 9. Zend_Date">
<link rel="chapter" href="zend.db.html" title="Chapter 10. Zend_Db">
<link rel="chapter" href="zend.debug.html" title="Chapter 11. Zend_Debug">
<link rel="chapter" href="zend.dojo.html" title="Chapter 12. Zend_Dojo">
<link rel="chapter" href="zend.dom.html" title="Chapter 13. Zend_Dom">
<link rel="chapter" href="zend.exception.html" title="Chapter 14. Zend_Exception">
<link rel="chapter" href="zend.feed.html" title="Chapter 15. Zend_Feed">
<link rel="chapter" href="zend.filter.html" title="Chapter 16. Zend_Filter">
<link rel="chapter" href="zend.form.html" title="Chapter 17. Zend_Form">
<link rel="chapter" href="zend.gdata.html" title="Chapter 18. Zend_Gdata">
<link rel="chapter" href="zend.http.html" title="Chapter 19. Zend_Http">
<link rel="chapter" href="zend.infocard.html" title="Chapter 20. Zend_InfoCard">
<link rel="chapter" href="zend.json.html" title="Chapter 21. Zend_Json">
<link rel="chapter" href="zend.layout.html" title="Chapter 22. Zend_Layout">
<link rel="chapter" href="zend.ldap.html" title="Chapter 23. Zend_Ldap">
<link rel="chapter" href="zend.loader.html" title="Chapter 24. Zend_Loader">
<link rel="chapter" href="zend.locale.html" title="Chapter 25. Zend_Locale">
<link rel="chapter" href="zend.log.html" title="Chapter 26. Zend_Log">
<link rel="chapter" href="zend.mail.html" title="Chapter 27. Zend_Mail">
<link rel="chapter" href="zend.measure.html" title="Chapter 28. Zend_Measure">
<link rel="chapter" href="zend.memory.html" title="Chapter 29. Zend_Memory">
<link rel="chapter" href="zend.mime.html" title="Chapter 30. Zend_Mime">
<link rel="chapter" href="zend.openid.html" title="Chapter 31. Zend_OpenId">
<link rel="chapter" href="zend.paginator.html" title="Chapter 32. Zend_Paginator">
<link rel="chapter" href="zend.pdf.html" title="Chapter 33. Zend_Pdf">
<link rel="chapter" href="zend.registry.html" title="Chapter 34. Zend_Registry">
<link rel="chapter" href="zend.rest.html" title="Chapter 35. Zend_Rest">
<link rel="chapter" href="zend.search.lucene.html" title="Chapter 36. Zend_Search_Lucene">
<link rel="chapter" href="zend.server.html" title="Chapter 37. Zend_Server">
<link rel="chapter" href="zend.service.html" title="Chapter 38. Zend_Service">
<link rel="chapter" href="zend.session.html" title="Chapter 39. Zend_Session">
<link rel="chapter" href="zend.soap.html" title="Chapter 40. Zend_Soap">
<link rel="chapter" href="zend.test.html" title="Chapter 41. Zend_Test">
<link rel="chapter" href="zend.text.html" title="Chapter 42. Zend_Text">
<link rel="chapter" href="zend.timesync.html" title="Chapter 43. Zend_TimeSync">
<link rel="chapter" href="zend.translate.html" title="Chapter 44. Zend_Translate">
<link rel="chapter" href="zend.uri.html" title="Chapter 45. Zend_Uri">
<link rel="chapter" href="zend.validate.html" title="Chapter 46. Zend_Validate">
<link rel="chapter" href="zend.version.html" title="Chapter 47. Zend_Version">
<link rel="chapter" href="zend.view.html" title="Chapter 48. Zend_View">
<link rel="chapter" href="zend.xmlrpc.html" title="Chapter 49. Zend_XmlRpc">
<link rel="appendix" href="requirements.html" title="Appendix A. Zend Framework Requirements">
<link rel="appendix" href="coding-standard.html" title="Appendix B. Zend Framework Coding Standard for PHP">
<link rel="appendix" href="copyrights.html" title="Appendix C. Copyright Information">
<link rel="index" href="the.index.html" title="Index">
<link rel="subsection" href="zend.controller.exceptions.html#zend.controller.exceptions.introduction" title="7.12.1. Introduction">
<link rel="subsection" href="zend.controller.exceptions.html#zend.controller.exceptions.handling" title="7.12.2. How can you handle exceptions?">
<link rel="subsection" href="zend.controller.exceptions.html#zend.controller.exceptions.internal" title="7.12.3. MVC Exceptions You May Encounter">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="navheader"><table width="100%" summary="Navigation header">
<tr><th colspan="3" align="center">7.12. MVC Exceptions</th></tr>
<tr>
<td width="20%" align="left">
<a accesskey="p" href="zend.controller.modular.html">Prev</a> </td>
<th width="60%" align="center">Chapter 7. Zend_Controller</th>
<td width="20%" align="right"> <a accesskey="n" href="zend.controller.migration.html">Next</a>
</td>
</tr>
</table></div>
<div class="sect1" lang="en">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="zend.controller.exceptions"></a>7.12. MVC Exceptions</h2></div></div></div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.controller.exceptions.introduction"></a>7.12.1. Introduction</h3></div></div></div>
<p>
            The MVC components in Zend Framework utilize a Front Controller,
            which means that all requests to a given site will go through a
            single entry point. As a result, all exceptions bubble up to the
            Front Controller eventually, allowing the developer to handle them
            in a single location.
        </p>
<p>
            However, exception messages and backtrace information often contain
            sensitive system information, such as SQL statements, file
            locations, and more. To help protect your site, by default
            <code class="code">Zend_Controller_Front</code> catches all exceptions and
            registers them with the response object; in turn, by default, the
            response object does not display exception messages.
        </p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.controller.exceptions.handling"></a>7.12.2. How can you handle exceptions?</h3></div></div></div>
<p>
            Several mechanisms are built in to the MVC components already to
            allow you to handle exceptions.
        </p>
<div class="itemizedlist"><ul type="disc">
<li>
<p>
                    By default, the <a href="zend.controller.plugins.html#zend.controller.plugins.standard.errorhandler" title="7.10.5.2. Zend_Controller_Plugin_ErrorHandler">error
                    handler plugin</a> is registered and active. This plugin
                    was designed to handle:
                </p>
<div class="itemizedlist"><ul type="circle">
<li><p>Errors due to missing controllers or actions</p></li>
<li><p>Errors occurring within action controllers</p></li>
</ul></div>
<p>
                    It operates as a <code class="code">postDispatch()</code> plugin, and
                    checks to see if a dispatcher, action controller, or
                    other exception has occurred. If so, it forwards to an error
                    handler controller.
                </p>
<p>
                    This handler will cover most exceptional situations, and
                    handle missing controllers and actions gracefully.
                </p>
</li>
<li>
<p><code class="code">Zend_Controller_Front::throwExceptions()</code></p>
<p>
                    By passing a boolean true value to this method, you can tell
                    the front controller that instead of aggregating exceptions
                    in the response object or using the error handler plugin,
                    you'd rather handle them yourself.  As an example:
                </p>
<pre class="programlisting">&lt;?php
$front-&gt;throwExceptions(true);
try {
    $front-&gt;dispatch();
} catch (Exception $e) {
    // handle exceptions yourself
}
                </pre>
<p>
                    This method is probably the easiest way to add custom
                    exception handling covering the full range of possible
                    exceptions to your front controller application.
                </p>
</li>
<li>
<p><code class="code">Zend_Controller_Response_Abstract::renderExceptions()</code></p>
<p>
                    By passing a boolean true value to this method, you tell the
                    response object that it should render an exception message
                    and backtrace when rendering itself. In this scenario, any
                    exception raised by your application will be displayed. This
                    is only recommended for non-production environments.
                </p>
</li>
<li>
<p>
                    <code class="code">Zend_Controller_Front::returnResponse()</code> and
                    <code class="code">Zend_Controller_Response_Abstract::isException()</code>.
                </p>
<p>
                    By passing a boolean true to
                    <code class="code">Zend_Controller_Front::returnResponse()</code>,
                    <code class="code">Zend_Controller_Front::dispatch()</code> will not render the
                    response, but instead return it. Once you have the response,
                    you may then test to see if any exceptions were trapped using
                    its <code class="code">isException()</code> method, and retrieving the exceptions via
                    the <code class="code">getException()</code> method. As an example:
                </p>
<pre class="programlisting">&lt;?php
$front-&gt;returnResponse(true);
$response = $front-&gt;dispatch();
if ($response-&gt;isException()) {
    $exceptions = $response-&gt;getException();
    // handle exceptions ...
} else {
    $response-&gt;sendHeaders();
    $response-&gt;outputBody();
}
                </pre>
<p>
                    The primary advantage this method offers over
                    <code class="code">Zend_Controller_Front::throwExceptions()</code> is to
                    allow you to conditionally render the response after
                    handling the exception. This will catch any exception in the
                    controller chain, unlike the error handler plugin.
                </p>
</li>
</ul></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="zend.controller.exceptions.internal"></a>7.12.3. MVC Exceptions You May Encounter</h3></div></div></div>
<p>
            The various MVC components -- request, router, dispatcher, action
            controller, and response objects -- may each throw exceptions on
            occasion. Some exceptions may be conditionally overridden, and
            others are used to indicate the developer may need to consider
            their application structure.
        </p>
<p>As some examples:</p>
<div class="itemizedlist"><ul type="disc">
<li>
<p>
                    <code class="code">Zend_Controller_Dispatcher::dispatch()</code> will,
                    by default, throw an exception if an invalid controller is
                    requested.  There are two recommended ways to deal with
                    this.
                </p>
<div class="itemizedlist"><ul type="circle">
<li>
<p>Set the <code class="code">useDefaultControllerAlways</code> parameter.</p>
<p>
                            In your front controller, or your dispatcher, add
                            the following directive:
                        </p>
<pre class="programlisting">&lt;?php
$front-&gt;setParam('useDefaultControllerAlways', true);

// or
$dispatcher-&gt;setParam('useDefaultControllerAlways', true);
                        </pre>
<p>
                            When this flag is set, the dispatcher will use the
                            default controller and action instead of throwing an
                            exception. The disadvantage to this method is that
                            any typos a user makes when accessing your site will
                            still resolve and display your home page, which can
                            wreak havoc with search engine optimization.
                        </p>
</li>
<li><p>
                            The exception thrown by <code class="code">dispatch()</code> is
                            a <code class="code">Zend_Controller_Dispatcher_Exception</code>
                            containing the text 'Invalid controller specified'.
                            Use one of the methods outlined in <a href="zend.controller.exceptions.html#zend.controller.exceptions.handling" title="7.12.2. How can you handle exceptions?">the
                                previous section</a> to catch the exception,
                            and then redirect to a generic error page or the
                            home page.
                        </p></li>
</ul></div>
</li>
<li>
<p>
                    <code class="code">Zend_Controller_Action::__call()</code> will throw a
                    <code class="code">Zend_Controller_Action_Exception</code> if it cannot
                    dispatch a non-existent action to a method. Most likely,
                    you will want to use some default action in the controller
                    in cases like this. Ways to achieve this include:
                </p>
<div class="itemizedlist"><ul type="circle">
<li>
<p>
                            Subclass <code class="code">Zend_Controller_Action</code> and
                            override the <code class="code">__call()</code> method. As an
                            example:
                        </p>
<pre class="programlisting">&lt;?php
class My_Controller_Action extends Zend_Controller_Action
{
    public function __call($method, $args)
    {
        if ('Action' == substr($method, -6)) {
            $controller = $this-&gt;getRequest()-&gt;getControllerName();
            $url = '/' . $controller . '/index';
            return $this-&gt;_redirect($url);
        }

        throw new Exception('Invalid method');
    }
}
                        </pre>
<p>
                            The example above intercepts any undefined action
                            method called and redirects it to the default action
                            in the controller.
                        </p>
</li>
<li>
<p>
                            Subclass <code class="code">Zend_Controller_Dispatcher</code>
                            and override the <code class="code">getAction()</code> method to
                            verify the action exists.  As an example:
                        </p>
<pre class="programlisting">&lt;?php
class My_Controller_Dispatcher extends Zend_Controller_Dispatcher
{
    public function getAction($request)
    {
        $action = $request-&gt;getActionName();
        if (empty($action)) {
            $action = $this-&gt;getDefaultAction();
            $request-&gt;setActionName($action);
            $action = $this-&gt;formatActionName($action);
        } else {
            $controller = $this-&gt;getController();
            $action     = $this-&gt;formatActionName($action);
            if (!method_exists($controller, $action)) {
                $action = $this-&gt;getDefaultAction();
                $request-&gt;setActionName($action);
                $action = $this-&gt;formatActionName($action);
            }
        }

        return $action;
    }
}
                        </pre>
<p>
                            The above code checks to see that the requested
                            action exists in the controller class; if not, it
                            resets the action to the default action.
                        </p>
<p>
                            This method is nice because you can transparently
                            alter the action prior to final dispatch. However,
                            it also means that typos in the URL may still
                            dispatch correctly, which is not great for search
                            engine optimization.
                        </p>
</li>
<li>
<p>
                            Use
                            <code class="code">Zend_Controller_Action::preDispatch()</code>
                            or
                            <code class="code">Zend_Controller_Plugin_Abstract::preDispatch()</code>
                            to identify invalid actions.
                        </p>
<p>
                            By subclassing <code class="code">Zend_Controller_Action</code>
                            and modifying <code class="code">preDispatch()</code>, you can
                            modify all of your controllers to forward to
                            another action or redirect prior to actually
                            dispatching the action. The code for this will look
                            similar to the code for overriding
                            <code class="code">__call()</code>, above.
                        </p>
<p>
                            Alternatively, you can check this information in a
                            global plugin. This has the advantage of being
                            action controller independent; if your application
                            consists of a variety of action controllers, and not
                            all of them inherit from the same class, this method
                            can add consistency in handling your various
                            classes.
                        </p>
<p>
                            As an example:
                        </p>
<pre class="programlisting">&lt;?php
class My_Controller_PreDispatchPlugin extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $dispatcher = Zend_Controller_Front::getInstance()-&gt;getDispatcher();
        $controller = $dispatcher-&gt;getController($request);
        if (!$controller) {
            $controller = $dispatcher-&gt;getDefaultControllerName($request);
        }
        $action     = $dispatcher-&gt;getAction($request);

        if (!method_exists($controller, $action)) {
            $defaultAction = $dispatcher-&gt;getDefaultAction();
            $controllerName = $request-&gt;getControllerName();
            $response = Zend_Controller_Front::getInstance()-&gt;getResponse();
            $response-&gt;setRedirect('/' . $controllerName . '/' . $defaultAction);
            $response-&gt;sendHeaders();
            exit;
        }
    }
}
                        </pre>
<p>
                            In this example, we check to see if the action
                            requested is available in the controller. If not, we
                            redirect to the default action in the controller,
                            and exit script execution immediately.
                        </p>
</li>
</ul></div>
</li>
</ul></div>
</div>
</div>
<div class="navfooter"><table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left">
<a accesskey="p" href="zend.controller.modular.html">Prev</a> </td>
<td width="20%" align="center"><a accesskey="u" href="zend.controller.html">Up</a></td>
<td width="40%" align="right"> <a accesskey="n" href="zend.controller.migration.html">Next</a>
</td>
</tr>
<tr>
<td width="40%" align="left" valign="top">7.11. Using a Conventional Modular Directory Structure </td>
<td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td>
<td width="40%" align="right" valign="top"> 7.13. Migrating from Previous Versions</td>
</tr>
</table></div>
<div class="revinfo"></div>
</body>
</html>
